import { constantRoutes } from '@/router/index'
import { menuDataTranslate } from '@/utils'
import { getInfo } from '@/api/user'
import Layout from '@/layout'
import { childrenRoutes } from '@/router/index'
import middleLayout from '@/layout/middleLayout'

import store from '@/store'

let modules = import.meta.glob('../../views/**/*.vue')

export const loadView = (view) => {
  const component = modules[`../../views${view}.vue`]
  return component
}

const findItem = (arr, itemId) =>
  arr.reduce((a, item) => {
    if (a) return a
    if (item.meta.menuId === itemId) return item
    if (item.children) return findItem(item.children, itemId)
  }, null)

const getDefaultState = () => {
  return {
    routes: [],
    addRoutes: [],
    hasRoutes: false
  }
}

/**
 * 把后台返回菜单组装成routes要求的格式
 */

export function getAsyncRoutes(routes) {
  const res = []
  const keys = ['path', 'name', 'children', 'meta', '_level']
  routes.forEach((item) => {
    const newItem = {}
    if (item.component) {
      if (item.component === 'layout/Layout') {
        newItem.component = Layout
        if (item._level === 2) {
          newItem.component = middleLayout
        }
      } else {
        try {
          newItem.component = loadView(item.component)
        } catch {
          newItem.component = null
        }
      }
    }
    for (const key in item) {
      if (keys.includes(key)) {
        newItem[key] = item[key]
      }
    }
    if (newItem.children && newItem.children.length) {
      newItem.children = getAsyncRoutes(item.children)
    }
    if (newItem.path) {
      res.push(newItem)
    }
  })
  return res
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes) {
  console.log(routes)
  routes.forEach((route) => {
    if (route.meta.menuId === 'M_12401002') {
      route.redirect = `${route.path}/operator/${store.getters.orgId}`
    }
    if (route.children && route.children.length === 1) {
      if (route.meta.menuId === 'M_144004') {
        route.alwaysShow = true
        route.redirect = route.path + route.children[0].path
      }
    } else if (route.children) {
      filterAsyncRoutes(route.children)
    }
  })
  return routes
}

function insertChildrenRoutes(asyncRoutes) {
  childrenRoutes.forEach((route) => {
    const _route = findItem(asyncRoutes, route.parentId)
    if (_route) {
      if (!_route.children) {
        _route.children = []
      }
      _route.children.push(route)
    }
  })
}

const state = getDefaultState()

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  RESET_ROUTES: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_HAS_ROUTES: (state, hasRoutes) => {
    state.hasRoutes = hasRoutes
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(async (resolve) => {
      const data = await getInfo() // 获取到后台路由
      const tomsMenu = data.platformInfoList.find(
        (list) => list.platCode === 'TOMS'
      )

      const filteredMenu = tomsMenu.menuList.filter((menu) => {
        return menu.showFlag === '1' && menu.platCode === 'TOMS'
      })

      const menuList = menuDataTranslate(filteredMenu, 'menuId', 'parentMenuId')
      const asyncRoutes = getAsyncRoutes(menuList) // 对路由格式进行处理
      const filteredRoutes = filterAsyncRoutes(asyncRoutes)
      insertChildrenRoutes(filteredRoutes)
      commit('SET_ROUTES', filteredRoutes)
      console.log(filteredRoutes)
      resolve(filteredRoutes)
    })
  },
  resetRoutes({ commit }) {
    commit('RESET_ROUTES')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
